/*
 * @Author: sunzhongjie
 * @Date: 2020-11-27 15:54:13
 * @LastEditors: Jelly
 * @LastEditTime: 2020-11-30 18:57:33
 */
const http = require('http') // 搭建HTTP web服务器
const ws = require('nodejs-websocket')
const fs = require('fs')
const path = require('path')

var hostname = '127.0.0.1'
var port = 3000

const EventEmitter = require('events')
const door = new EventEmitter()
console.log('MaxListeners: ', door.getMaxListeners())

var app = http.createServer((req, res) => {
  fs.readFile(__dirname + '/websocket.html', function(err, data) {
    if(err) {
      res.writeHead(500)
      return res.end('error: 程序异常已结束!')
    }
    res.writeHead(200, { 'Sec_WebSocket-Protocol': 'chat' })
    res.end(data)
  })
})
var server = ws.createServer(function(conn) {
  console.log('new connection')
  conn.on('text', function(str) {
    broadcast(server, str)
  })
  conn.on('close', function(code, reason) {
    console.log(`connection closed, code: ${code}, reason: ${reason}`)
  })
}).listen(5000)

function broadcast(server, msg) {
  console.log('broadcast: ', msg)
  server.connections.forEach((conn) => {
    conn.sendText(msg)
  })
}

app.listen(port, hostname, () => {
  console.log(`服务器运行在 http://${hostname}:${port}`)
})
